package com.jemaa.news.web;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jemaa.news.app.Contact;
import com.jemaa.news.app.NotificationService;
import com.jemaa.news.exceptions.ContactError;
import com.jemaa.news.exceptions.JemaaException;

/**
 *
 * Controlleur Web pour les actions sur les contacts. 
 *
 **/

@Controller
@RequestMapping("/contact/*")
public class ContactController {

	private NotificationService notificationServcie;

	
	@Autowired
	public void setNotificationServcie(NotificationService notificationServcie) {
		this.notificationServcie = notificationServcie;
	}

	@RequestMapping(value = "index", method = RequestMethod.GET)
	public void index(Contact contact){
	}
	
	
	@RequestMapping(value = "cancel", method = RequestMethod.POST)
	public void cancel(){
	}
	
	@RequestMapping(value = "notification", method = RequestMethod.GET)
	public void notification(){
	}
	
	@RequestMapping(value = "send", method = RequestMethod.POST)
	public String send(Contact contact, BindingResult bindResult) throws Exception{
		
		try {
			if (StringUtils.isBlank(contact.getAuthor())) {
				bindResult.rejectValue("author", "required",
					"Saisissez un nom valide");
			}
			
			if (!EmailValidator.getInstance().isValid(contact.getAddress())) {
				bindResult.rejectValue("address", "required",
					"Saisissez une adresse valide");
			}
			
			if (StringUtils.isBlank(contact.getSubject())) {
				bindResult.rejectValue("subject", "required",
					"Saisissez un sujet valide");
			}
			
			if (StringUtils.isBlank(contact.getMessage())) {
				bindResult.rejectValue("message", "required",
					"Saisissez un message valide");
			}
			
			if (bindResult.hasErrors()) {
				return "contact/index";
			} else {
				
				notificationServcie.sendContact(contact);
				
				return "contact/notification";
			}
		} catch (JemaaException e) {
		  throw new ContactError(e.getMessage());
		}
		
		
	}
	
}
